import { Text, View } from '@tarojs/components';
import React, { createContext, useContext, useState } from 'react';
import theme from '@/theme';
import Divider from '../Divider';
import BoxShadow from '../BoxShadow';
import './index.scss';
import Icon from '../Icon';

const context = createContext({ group: false });

const Root = ({ children, radius, ...props }) => {
  const { group } = useContext(context);
  const [hover, setHover] = useState(false);

  if (group) {
    return (
      <View
        className='pd-cell pd-cellItem'
        {...props}
        hoverStyle={hover ? props.hoverStyle || { opacity: 0.8 } : {}}
        onTouchStart={() => {
          setHover(true);
        }}
        onTouchMove={() => {
          setHover(false);
        }}
        onTouchEnd={() => {
          setHover(false);
        }}>
        {children}
        {!!props.isLink && <Icon name='right' color={theme.common.colorValue} size={32} />}
      </View>
    );
  }
  return (
    <BoxShadow className='pd-cell' radius={radius} {...props}>
      {children}
    </BoxShadow>
  );
};

const Group = ({ line = true, radius = theme.common.radiusValue, children }) => {
  return (
    <>
      <BoxShadow className='pd-cellGroup' radius={radius}>
        <context.Provider value={{ group: true }}>
          {line
            ? React.Children.map(children, (child, index) => {
                return (
                  <React.Fragment key={index}>
                    {index !== 0 && <Divider padding={0} />}
                    {child}
                  </React.Fragment>
                );
              })
            : children}
        </context.Provider>
      </BoxShadow>
    </>
  );
};

const Cell = ({ title, subTitle, desc, renderIcon, isLink, radius = theme.common.radiusValue, ...props }) => {
  return (
    <Root radius={radius} isLink={isLink} {...props}>
      <View className={`pd-cell__left${subTitle ? ' pd-cell__left--col' : ''}`}>
        {!!renderIcon && !subTitle && <View className='pd-cell__icon'>{renderIcon}</View>}
        {React.isValidElement(title) ? title : <Text className='pd-cell__title'>{title}</Text>}
        {!!subTitle && (React.isValidElement(subTitle) ? subTitle : <Text className='pd-cell__subtitle'>{subTitle}</Text>)}
      </View>
      {React.isValidElement(desc) ? (
        desc
      ) : (
        <View className='pd-cell__right'>
          <Text className='pd-cell__desc'>{desc}</Text>
        </View>
      )}
    </Root>
  );
};

Cell.Group = Group;
export default Cell;
